/**
 * Created by tangqiaojie <2482366539@qq.com> on 2020/3/30 0030
 */

import { nextTick } from '../../lib/utils.js';
import { sendSbList } from './tool.js';
import { asyncSetInterval } from '../../lib/zeroReportUtils.js';

const saveTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: 'asyncTableDetail',
      data: tableContent
    },
    '*'
  );
};

const sendTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: 'asyncTableDetailRequest'
    },
    '*'
  );
};

const saveTable = (name, url, time)=>{
  let declareType = '';
  if (name.includes('中华人民共和国企业所得税月')) {
    declareType = '企业所得税(月季报)';
  } else if (name.includes('中华人民共和国企业所得税年度')) {
    declareType = '企业所得税(年报)';
  } else if (name.includes('附加税')) {
    declareType = '地方教育附加';
  } else if (name.includes('增值税纳税申报表（小规模纳税人适用）')) {
    declareType = '增值税(适用于小规模纳税人)';
  }
  let tableContent = {
    declareType,
    title: name,
    url: url
  };
  setTimeout(()=>{
    saveTableDetail(tableContent);
  }, time * 500);
};

const downloadPDF = async (pzxh, version, gdslxDm, ysqxxid, ywbm, win)=>{
  return new Promise((resolve, reject)=>{
    var top = 'auto';// 默认自动
    try {
      if (win.top == win.self) {
        // 不存在父页面
      } else {
        top = win.parent.document.documentElement.scrollTop + 200 + 'px';
      }
    } catch (e) {}
    var index = win.layer.load(2, { offset: top, time: 10 * 500, shade: 0.1 });
    var openPdfurl = 'openPdf.do?pzxh=' + pzxh + '&version=' + version + '&gdslxDm=' + gdslxDm + '&ysqxxid=' + ysqxxid;
    console.log(openPdfurl);
    win.$.ajax({
      url: openPdfurl,
      type: 'GET',
      data: {},
      dataType: 'json',
      contentType: 'application/json',
      success: function(data) {
        var pdfurl = eval('(' + data + ')');
        if (version == '1' || version == '3') {
          if (pdfurl == null || pdfurl == '') {
            return;
          }
        }
        var url = 'https://etax.beijing.chinatax.gov.cn/zlpz-cjpt-web/zlpz/viewOrDownloadPdfFile.do?ysqxxid=' + ysqxxid + '&viewOrDownload=download&gdslxDm=' + gdslxDm + '&ywbm=' + ywbm + '&DZSWJ_TGC=' + win.DZSWJ_TGC;
        resolve(url);
      },
      error: function(e) {
        reject(e);
      },
      complete: function() {

      },
      timeout: 1000000000
    });
  });
};


const getTables = ()=>{
  $("[mflag='sbcxjdy']").click();
  nextTick(()=>{
    if ($('#ifrMain').length && $('#ifrMain')[0].contentWindow) {
      let win = $('#ifrMain')[0].contentWindow;
      if (win.$('.layui-btn-primary').length) {
        win.$('.layui-btn-primary').click();
        nextTick(()=>{
          if (win.$('#viewCtrlid tr.ng-scope').length) {
            // win.cxDownloadPDF=downloadPDF;
            win.$('#viewCtrlid tr.ng-scope').each((index, item)=>{
              // saveTable($("[ng-bind='item.ywbmmc']",item).html())
              let res = $('.layui-btn:eq(1)', item).attr('onclick').split("'");
              downloadPDF(res[1], res[3], res[5], res[7], res[9], win).then(res=>{
                saveTable($("[ng-bind='item.ywbmmc']", item).html(), res, index);
              });
            });
            setTimeout(()=>{
              sendTableDetail();
            }, 5000);
            return true;
          }
        });
        return true;
      }
    }
  }, 3000);
};

let startAsyncTable = () => {
  document.querySelector('#mainContent > table > tbody > tr > td.left_box > div > ul > li:nth-child(6) > a').click();
  document.querySelector('#mainContent > table > tbody > tr > td.left_box > div > ul > li:nth-child(6) > ul > li:nth-child(1) > a').click();
  asyncSetInterval(() => {
    let ifrMain = $('#ifrMain');
    if (ifrMain.length) {
      ifrMain[0].contentWindow.queryBtn();
      return true;
    }
  }, 2000).then(() => {
    return asyncSetInterval(async () => {
      let ifrMain = $('#ifrMain').contents();
      let names = ifrMain.find('#dataList > tbody > tr');
      if (names.length) {
        let zzs = Array.from(names).find(tr => $(tr).find('td:nth-child(2)').text().includes('增值税纳税申报表（小规模纳税人适用'));
        let fjs = Array.from(names).find(tr => $(tr).find('td:nth-child(2)').text().includes('附加税（费）纳税申报表'));
        let qysds = Array.from(names).find(tr => $(tr).find('td:nth-child(2)').text().includes('中华人民共和国企业所得税月'));
        let index = 1;
        if (zzs) {
          let btn = $(zzs).find('td.ng-scope > button:nth-child(2)');
          let res = btn.attr('onClick').split("'");
          let rs = await downloadPDF(res[1], res[3], res[5], res[7], res[9], $('#ifrMain')[0].contentWindow);
          saveTable($(zzs).find('td:nth-child(2)').html(), rs, index);
          index++;
          console.log(444)
        }
        if (fjs) {
          let btn = $(fjs).find('td.ng-scope > button:nth-child(2)');
          let res = btn.attr('onClick').split("'");
          let rs = await downloadPDF(res[1], res[3], res[5], res[7], res[9], $('#ifrMain')[0].contentWindow);
          saveTable($(fjs).find('td:nth-child(2)').html(), rs, index);
          index++;
          console.log(333);
        }
        if (qysds) {
          let btn = $(qysds).find('td.ng-scope > button:nth-child(2)');
          let res = btn.attr('onClick').split("'");
          let rs = await downloadPDF(res[1], res[3], res[5], res[7], res[9], $('#ifrMain')[0].contentWindow)
          saveTable($(qysds).find('td:nth-child(2)').html(), rs, index);
          index++;
          console.log(222);
        }
        setTimeout(()=>{
          sendTableDetail();
        }, 1000);
        return true;
      }
    }, 2000);
  });
};


export {
  saveTableDetail,
  getTables,
  startAsyncTable
};
